layui.use(function() {
  var $ = layui.$;
  var form = layui.form;
  var layer = layui.layer;

  let image_code_uuid = generateUUID();
  document.getElementById(
      'captchaImage').src = `/get_captcha?image_code_uuid=${image_code_uuid}`;

  $('#captchaImage').click(function() {
    image_code_uuid = generateUUID();
    document.getElementById(
        'captchaImage').src = `/get_captcha?image_code_uuid=${image_code_uuid}`;
  });

  // 提交事件
  form.on('submit(demo-login)', function(data) {
    var field = data.field; // 获取表单字段值
    field['image_code_uuid'] = image_code_uuid;
    fetch(`/login${location.search}`, {
      method: 'POST',
      headers: {'Content-Type': 'application/json'},
      body: JSON.stringify(field),
    }).then(function(response) {
      return response.json();
    }).then(function(ret) {
      if (!ret.code) {
        // 登录成功回调到首页，或者跳转到被拦截的页面
        // 存储到本地的 localStorage
        localStorage.setItem('access_token', ret.access_token);

        // .next
        layer.msg(ret.message, {icon: 1}, function() {
          setTimeout(function() {
            // 如果有 next 就调整过去
            location.href = ret?.next ? ret.next : '/';
          }, 1000);
        });
      } else {
        layer.msg(ret.message, {icon: 0});
      }
    });
    return false; // 阻止默认 form 跳转
  });

  // 定时器，定时更新验证码
  setInterval(function() {
    let imageCodeId = generateUUID();
    document.getElementById('captchaImage').src = '/passport/getCaptcha' +
        '?image_code=' +
        imageCodeId;
  }, 50 * 1000);

  // 生成 uuid
  function generateUUID() {
    var d = new Date().getTime();
    if (window.performance && typeof window.performance.now === 'function') {
      d += performance.now(); //use high-precision timer if available
    }
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g,
        function(c) {
          var r = (d + Math.random() * 16) % 16 | 0;
          d = Math.floor(d / 16);
          return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
        });
  }

});